package team.chuangshu.lm.auth;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import team.chuangshu.lm.service.UserService;

import java.util.List;

/**
 * @auther zhang
 * @ TO DO
 * @creatTime 2019/5/9 21:16
 **/
@Component
@Slf4j
public class userDetailService implements UserDetailsService {


    @Autowired
    private UserService userService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("登录用户名 : {}", username);
        List<team.chuangshu.lm.entity.User> userList;

        // 根据用户名查找用户信息
        try {
            team.chuangshu.lm.entity.User user = new team.chuangshu.lm.entity.User();
            user.setUserId(username);
            userList = userService.findByParams(user);
            log.info("1"+userList.toString());
        } catch (Exception e) {
            throw new UsernameNotFoundException("系统异常");
        }
        log.info(userList.toString());
        if (userList.size() == 0) {
            log.info(userList.toString());
            throw new BadCredentialsException("用户名不存在!");
        }

        if (userList.size() > 1) {
            log.info(userList.toString());
            throw new BadCredentialsException("系统异常");
        }

        String userPassword = userList.get(0).getPassword();

        return new User(username, userPassword,
                AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
    }

}